import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routers'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import { getToken } from "@/libs/auth";

// 多次点击跳转同一个路由是不被允许的
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)
const router = new VueRouter({
    routes
})


// 免登录白名单中
const whiteList = ['/login', '/forget', '/401', '/404', '/500']
// 登录页面
const LOGIN_PAGE_NAME = 'login'

router.beforeEach((to, from, next) => {
    //开启NProgress进度条
    NProgress.configure({ showSpinner: false });
    NProgress.start()

    // 获取登录token
    const token = getToken()

    if (whiteList.indexOf(to.path) !== -1) {
        next()
    } else {
        if (!token && to.name !== LOGIN_PAGE_NAME) {
            // 未登录且要跳转的页面不是登录页
            next({
                name: LOGIN_PAGE_NAME // 跳转到登录页
            })
        } else if (!token && to.name === LOGIN_PAGE_NAME) {
            // 未登陆且要跳转的页面是登录页
            next() // 跳转
        } else if (token && to.name === LOGIN_PAGE_NAME) {
            // 已登录且要跳转的页面是登录页，跳转到主页
            next({ name: 'main' })
        } else {
            next()
        }
    }
})

router.afterEach(to => {
    NProgress.done() //结束NProgress进度条
})

export default router
